<?php
class forPhoneModel extends MySQL {
	function __construct() {
		MySQL::connect();
	}
	//將每個功能新增成function放在下面
	function android($try) {
		$link = MySQL::connect();
		if ($try == "try") {
			$sql = "select shopid, fullname, address from shops";
			$result = mysqli_query($link, $sql);
			while($e=mysqli_fetch_assoc($result))
				$output[]=$e;
			print(json_encode($output));
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function GCM_send($gcm_regid, $str) {
		require_once(Models_DIR.'GCM.php');
		$gcm = new GCM();
		$registatoin_ids = array($gcm_regid);
		$message = array("price" => $str);
		$result = $gcm->send_notification($registatoin_ids, $message);
		return $result;
	}

	function gethours_key($time){
	  //從statistics取出與$time同樣的weekday
	  //判斷出是早、中、下、晚，用 $time_section來表示
	  $hours_key = date('H',strtotime($time));
	  if ($hours_key >= 0 && $hours_key <= 11) $time_section = '早';
	  elseif ($hours_key <= 14) $time_section = '中';
	  elseif ($hours_key <= 17) $time_section = '下';
	  elseif ($hours_key <= 23) $time_section = '晚';
	  return $time_section;
	}

	function getweek($time){
		//$_week存放著禮拜幾，$week_key取$time的weekday
	  $_week=array('日','一','二','三','四','五','六');
	  $week_key=date('w',strtotime($time));
	  return $_week[$week_key];
	}

	function getTableType($tmp){
		//$tmp1 代表著桌種，$tmp2 代表相近的桌種
		if($tmp<=2){
		 	return 2;
		}elseif($tmp<=4){
		 	return 4;
		}elseif($tmp<=6){
		 	return 6;
		}elseif($tmp<=8){
		 	return 8;
		}else{
		 	print_r("Over eight people!!!");
		 	die();
		}
	}

	function getSimilarType($tmp){
		if($tmp<=2){
		 	return 1;
		}elseif($tmp<=4){
		 	return 3;
		}elseif($tmp<=6){
		 	return 5;
		}elseif($tmp<=8){
		 	return 7;
		}else{
		 	print_r("Over eight people!!!");
		 	die();
		}
	}

	function getComment($str) {
		if ($str['shopid'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$shopid = $new_str['shopid'];
			$link = MySQL::connect();
			$sql = "SELECT nickname, comments, rank FROM comment WHERE shopid = '$shopid'";
			$result = mysqli_query($link, $sql);
			while ($row = mysqli_fetch_row($result)) {
				$nickname = $row[0];
				$comment = $row[1];
				$rank = $row[2];
				$return[] = array(
								"nickname" => $nickname,
								"comments" => $comment,
								"rank" => $rank
							);
			}
			print(json_encode($return));
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function qryWTime($str){      //演算法算出時間
	  $new_str = forPhoneModel::SQL_Injection($str);
		$shopid = $new_str['shopid'];
		$orderofnum = $new_str['orderofnum'];
		$time = $new_str['phonetime'];
		$output_ary = array();
		$rst_tmp = array();
   //先取得店內與orderofnum相近的桌數
    if($orderofnum>0 AND $orderofnum <= 8){
     //$tabletype 代表著桌種，$tmp1 代表相近的桌種
      $tabletype = forPhoneModel::getTableType($orderofnum);
      $tmp1 = forPhoneModel::getSimilarType($orderofnum);
     //$row_getTablenum[0] 代表桌種，$row_getTablenum[1]代表桌種數量
      $sql_getTablenum = "SELECT type, totalnumber FROM tables WHERE shopid = '$shopid' AND type = $tabletype;";
      $row_getTablenum = MySQL::query_row($sql_getTablenum);
     //算出排隊人數(flag = -1)
     //$row_getQueue，拿ordertime 與 phonetime作比較，算出目前占據一樣桌種的數量
      $sql_getQueue = "SELECT COUNT(*) FROM (SELECT * FROM client WHERE shopid = '$shopid' AND ordertime<'$time' AND flag = '-1' AND (orderofnum = '$tabletype'  OR orderofnum = '$tmp1')) AS tmp";
      //echo $sql_getQueue;
      $row_getQueue = MySQL::query_row($sql_getQueue);
    //從statistics取出與$time同樣的weekday
    //判斷出是早、中、下、晚，用 $time_section來表示
      $time_section = forPhoneModel::gethours_key($time);
    //$_week存放著禮拜幾，$week_key取$time的weekday
      $weekday = forPhoneModel::getweek($time);
      $sql_getAVGtime = "SELECT avgDiningTime FROM statistics WHERE shopid = '$shopid' AND section = '$weekday/$time_section' AND tabletype = '$tabletype';";
      $row_getAVGtime = MySQL::query_row($sql_getAVGtime);
    //算出user是取店內用餐第幾久的客人的用餐時間
    //自己的排隊號
      $queueUpNumber = $row_getQueue[0] + 1;
    //$queue_key 代表取第幾筆資料
      $queue_key = $queueUpNumber % $row_getTablenum[1];
      if($queue_key==0) $queue_key = $row_getTablenum[1];
    //取店內第 $queue_key 筆資料
      $sql = "SELECT * FROM ( SELECT * FROM `client` WHERE shopid = '$shopid' AND (orderofnum = '$tabletype'  OR orderofnum = '$tmp1') ORDER BY  clientid, arrivetime ASC LIMIT $queue_key  ) AS temp1 ORDER BY arrivetime DESC LIMIT 1";
      $rst = MySQL::query_row($sql);
      $nowtime = date_create($time);
      $arrtime = date_create($rst[6]);
      $dining = date_diff($nowtime,$arrtime);
      $diningTime = $dining->format('%H')*60+$dining->format('%i');
      if($nowtime->format('h:i:d')<$arrtime->format('h:i:d')) $diningTime *= -1;
      /*echo $nowtime->format('h:i').'</br>';
      echo $arrtime->format('h:i').'</br>';
      echo $rst[6].'</br>';
      echo $diningTime;
      die();*/
      $rst_tmp['queueUpNumber'] = $queueUpNumber;
      //echo $queueUpNumber.'</br>';
      if($row_getQueue[0] <= $row_getTablenum[1]){ 	    //等待人數還未超過店內一樣桌種桌數
        if(($row_getAVGtime[0]-$diningTime)<0){
        	$rst_tmp['isNagative'] = 1;
        	$rst_tmp['waitingtime'] = ($row_getAVGtime[0]*1.5-$diningTime);
        }else{
        	$rst_tmp['isNagative'] = 0;
        	$rst_tmp['waitingtime'] = ($row_getAVGtime[0]-$diningTime);
        }
      }else{	    //等待人數超過店內一樣桌種桌數
        if(($row_getAVGtime[0]-$diningTime)<0){
        	$rst_tmp['isNagative'] = 1;
        	$rst_tmp['waitingtime'] = ($row_getAVGtime[0]+($row_getAVGtime[0]*1.5-$diningTime))	;
        }else{
        	$rst_tmp['isNagative'] = 0;
        	$rst_tmp['waitingtime'] = ($row_getAVGtime[0]+($row_getAVGtime[0]-$diningTime));
        }
      }
      array_push($output_ary, $rst_tmp);
      return json_encode($output_ary);
    }elseif ($orderofnum > 8){
      print_r("Over eight people !");
      die();
    }else{
      print_r("Error !!!");
      die();
    }
	}

	function client_checkin($str) {
		if ($str['phonetime'] != null && $str['shopid'] != null && $str['clientname'] != null && $str['orderofnum'] != null && $str['cellphone'] != null && $str['queue'] != null && $str['imsi'] != null && $str['gcm_regid'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$time = $new_str['phonetime'];
			$shopid = $new_str['shopid'];
			$clientname = $new_str['clientname'];
			$orderofnum = $new_str['orderofnum'];
			$cellphone = $new_str['cellphone'];
			$queue = $new_str['queue'];
			$imsi = $new_str['imsi'];
			$gcm_regid = $new_str['gcm_regid'];
			$tabletype = forPhoneModel::getTableType($orderofnum);
			//檢查客戶有沒有對同一間餐廳重複訂位
			$sql = "SELECT * FROM client WHERE shopid = '$shopid' AND imsi = '$imsi'";
			$result = MySQL::query_row($sql);
			if ($result != NULL) {
				print_r('重複訂位，訂位取消');
				die();
			}
			//進行訂位
			if ($queue == 0) {
				//計算此使用者在系統內訂位的數量，如果超過三次就不可以訂位
				$sql = "SELECT COUNT(*) FROM client WHERE imsi = '$imsi'";
				$result = MySQL::query_row($sql);
				if ($result[0] > 3) {
					print_r('滿三次');
					die();
				} else {
					//沒有在系統超過三次訂位，繼續訂位程序
						$sql = "SELECT maxofnumber, currentnumber FROM shops WHERE shopid='$shopid'";
						$result = MySQL::query_array($sql);
						$maxofnumber = $result['maxofnumber'];
						$currentnumber = $result['currentnumber'];

					//可以訂位
						$currentnumber += $orderofnum;
						$sql = "UPDATE shops set currentnumber = '$currentnumber' WHERE shopid = '$shopid'";
						MySQL::query($sql);
						$maxofnumber-=$tabletype;
						$sql = "UPDATE shops set maxofnumber = '$maxofnumber' WHERE shopid = '$shopid'";
						MySQL::query($sql);
					//arrive time = $time + 10 minutes;
						$arrivetime = date("Y-m-d H:i", strtotime('+10 minutes',strtotime($time)));
						$sql = "INSERT INTO client VALUES(NULL, '$shopid', '$clientname', '$orderofnum', '$cellphone', '$time', '$arrivetime', '$imsi', '$gcm_regid', 0)";
						MySQL::query($sql);
						forPhoneModel::GCM_send($gcm_regid, '請於10分鐘內到店');
					//}
				}
			}else if ($queue == 1) {
			//此處用演算法計算出時間
				$tmp = json_decode(forPhoneModel::qryWTime($new_str));
				$waitingtime = $tmp[0]->waitingtime;
				$sql = "INSERT INTO `client`(`shopid`,`clientname`,`orderofnum`,`cellphone`,`ordertime`,`imsi`,`gcm_regid`,`flag`) VALUES('$shopid', '$clientname', '$orderofnum', '$cellphone', '$time', '$imsi', '$gcm_regid', -1)";
				MySQL::query($sql);
				forPhoneModel::GCM_send($gcm_regid, '請於'.$waitingtime.'分鐘內到店');//這裡的時間要用演算法算出的時間
			}else
				forPhoneModel::errorMsg('queue error');
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function getShopStatus($str) {
		if ($str['shopid'] != null && $str['orderofnum'] != null) {
			$link = MySQL::connect();
			$rst_tmp = array();
			$output_ary = array();
			$new_str = forPhoneModel::SQL_Injection($str);
			$shopid = $new_str['shopid'];
			$orderofnum = $new_str['orderofnum'];
			$shopid = $new_str['shopid'];
			$time = $new_str['phonetime'];
			$time_section = forPhoneModel::gethours_key($time);
			$weekday = forPhoneModel::getweek($time);
	   //先取得店內與orderofnum相近的桌數
	   //$tmp 代表著桌種，$tmp1 代表相近的桌種
	    $tabletype = forPhoneModel::getTableType($orderofnum);
	  	$tmp1 = forPhoneModel::getSimilarType($orderofnum);
	   //取得店內人數以及現在人數
			$sql = "SELECT maxofnumber, currentnumber FROM shops WHERE shopid = '$shopid'";
			$row = MySQL::query_row($sql);
			if($row[0]==0){
				$rst_tmp['maxofnumber'] = 0;
	    	array_push($output_ary, $rst_tmp);
	    	print_r(json_encode($output_ary));
	    	die();
			}else{
				$maxofnumber = $row[0];
				$currentnumber = $row[1];
		  //$row_getTablenum[0] 代表桌種，$row_getTablenum[1]代表桌種數量
		    $sql_getTablenum = "SELECT type, totalnumber FROM tables WHERE shopid = '$shopid' AND type = $tabletype;";
		    $row_getTablenum = MySQL::query_row($sql_getTablenum);
			//$row_getQueue算出目前占據一樣桌種的數量
			  $sql_getInside = "SELECT COUNT(*) FROM (SELECT * FROM client WHERE shopid = '$shopid' AND (flag = '0'  OR flag = '$tabletype') AND (orderofnum = '$tabletype'  OR orderofnum = '$tmp1')) AS tmp";
			  $row_getInside = MySQL::query_row($sql_getInside);
		    if($row_getTablenum[1]==0){
					$rst_tmp['maxofnumber'] = 0;
		    	array_push($output_ary, $rst_tmp);
		    	print_r(json_encode($output_ary));
		    	die();
		    }
				elseif (($row_getTablenum[1]-$row_getInside[0])>0){	//queue==0
					$rst_tmp['status'] = 'OK!!';
		    	array_push($output_ary, $rst_tmp);
		    	print_r(json_encode($output_ary));
					forPhoneModel::client_checkin($new_str);
				}
				else{																						//queue==1
					print_r(forPhoneModel::qryWTime($new_str));
				}
			}
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");

	}

	function getTime($str) {
		if ($str['imsi'] != null) {
			//$return = array();
			$new_str = forPhoneModel::SQL_Injection($str);
			$imsi = $new_str['imsi'];
			$time = $new_str['phonetime'];
     	$nowtime = date_create($time);
			$link = MySQL::connect();
			$sql = "SELECT `shopid`, `flag`, `arrivetime`, `orderofnum` , `ordertime` FROM `client` WHERE imsi = '$imsi'";
			$rst = mysqli_query($link, $sql);
			if ($rst) {
				while ($row = mysqli_fetch_row($rst)) {
					$shopid = $row[0];
					$flag = $row[1];
					if($flag == '0') {		//有位置
			      $arrtime = date_create($row[2]);
			      $count = date_diff($nowtime,$arrtime);
			      $countdown = $count->format('%H')*60+$count->format('%i');
						$return[] = array(
								'shopid' => $shopid,
								'time' => $countdown,
								'flag' => $flag
								);
					}else if($flag == '-1') {		//要排隊
						$tmp = array();
						$tmp['shopid'] = $shopid;
						$tmp['orderofnum'] = $row[3];
						$tmp['phonetime'] = $row[4];
						$tmp01 = json_decode(forPhoneModel::qryWTime($tmp));
						$return[] = array(
								'shopid' => $shopid,
								'queueUpNumber' => $tmp01[0]->queueUpNumber,
								'time' => $tmp01[0]->waitingtime,
								'flag' => $flag
								);
					}else {		// 用餐中
						$return[] = array(
								'shopid' => $shopid,
								'time' => '0',
								'flag' => $flag
								);
					}
				}
				if($row === FALSE) {
					if(count($return) == 0) {
						$sql = "SELECT `shopid` FROM `statistics` WHERE `imsi` = '$imsi' ORDER BY leavetime DESC limit 1";
						$row = MySQL::query_row($sql);
						$shopid = $row[0];
						$return[] = array(
								'shopid' => $shopid,
								'time' => '-2',
								'flag' => '-2'
						);
					}
				}else{
					print(json_encode($return));
				}
			}
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}
//主要是在取得shop information其中包含maxofnumber 和 currentofnumber
	function httpPostTest($str) {
		if ($str['shopid'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$shopid = $new_str['shopid'];
			$link = MySQL::connect();
			$sql = "SELECT * FROM shops WHERE shopid = '$shopid'";
			$result = mysqli_query($link, $sql);
			while ($e = mysqli_fetch_array($result))
				$output[] = $e;
			print(json_encode($output));
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function listStatus($str){
		if ($str['phonetime'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$link = MySQL::connect();
			$shopid_ary = array();
			$tabletype_ary = array();
			$wait_flag_ary = array();
			$table_status_ary = array();
			$output_ary = array();
			$rst_tmp = array();
			$time = $new_str['phonetime'];
			$time_section = forPhoneModel::gethours_key($time);
			$weekday = forPhoneModel::getweek($time);
	    $sql = "SELECT shopid, tabletype,  avgDiningTime FROM `statistics` WHERE section = '$weekday/$time_section' ORDER BY shopid, tabletype ASC;";
	    $result = mysqli_query($link, $sql);
	    while($e = mysqli_fetch_array($result)){
		    //$tmp1 代表著桌種，$tmp2 代表相近的桌種
	    	$tmp1 = forPhoneModel::getTableType($e[1]);
	    	$tmp2 = forPhoneModel::getSimilarType($e[1]);
	    	//計數client表中該店flag=2,4,6,8的人數, 以$rst_pnum[0]表示
	    	$sql_tmp = "SELECT COUNT(*) FROM (SELECT shopid, flag FROM `client` WHERE shopid = '$e[0]' AND (flag = '$e[1]' OR ((orderofnum = '$tmp1' OR orderofnum = '$tmp2') AND flag = '0'))) AS tmp";
	    	$rst_pnum = MySQL::query_row($sql_tmp);
	    	//找出該店同桌種的總數
	    	$sql_tmp = "SELECT shopid, type, totalnumber FROM `tables` WHERE shopid = '$e[0]' AND type = '$e[1]'";
	    	$rst_tnum = MySQL::query_row($sql_tmp);
	    	if($rst_tnum[2] == 0) {	//不提供該桌種
	    		$wait_flag = -1;
	    		$table_status = -1;
	    	}
	    	elseif (($rst_tnum[2]-$rst_pnum[0])>0){
	    		$wait_flag = 0;
					$table_status = $rst_tnum[2]-$rst_pnum[0];
	    	}else {
	    		$wait_flag = 1;
	    		$table_status = $e[2];
	    	}
				array_push($shopid_ary, $e[0]);
				array_push($tabletype_ary, $e[1]);
				array_push($wait_flag_ary, $wait_flag);
				array_push($table_status_ary, $table_status);
			}
			$tmp = null;
			$tmp_flag = 0; // 0 代表不要array_push, 1 則反之
			for($i=0;$i<sizeof($shopid_ary);$i++){
				if($tmp != $shopid_ary[$i]){
					$tmp = $shopid_ary[$i];
					$rst_tmp['shopid'] = $tmp;
					$tmp_flag	= 0;
				}
				if(isset($shopid_ary[$i+1]) == NULL or $tmp != $shopid_ary[$i+1]) $tmp_flag = 1;
				if($tabletype_ary[$i] == 2){
					$rst_tmp['wait_flag_2'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_2'] = $table_status_ary[$i];
				}elseif($tabletype_ary[$i] == 4){
					$rst_tmp['wait_flag_4'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_4'] = $table_status_ary[$i];
				}elseif($tabletype_ary[$i] == 6){
					$rst_tmp['wait_flag_6'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_6'] = $table_status_ary[$i];
				}elseif($tabletype_ary[$i] == 8){
					$rst_tmp['wait_flag_8'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_8'] = $table_status_ary[$i];
				}
				if($tmp_flag == 1) array_push($output_ary, $rst_tmp);
			}
			print(json_encode($output_ary));
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function listTableStatus($str){
		if ($str['phonetime'] != null && $str['shopid'] != null) {
			$link = MySQL::connect();
			$new_str = forPhoneModel::SQL_Injection($str);
			$tabletype_ary = array();
			$wait_flag_ary = array();
			$table_status_ary = array();
			$output_ary = array();
			$rst_tmp = array();
			$maxofnumber = 0;
			$time = $new_str['phonetime'];
			$shopid = $new_str['shopid'];
			$time_section = forPhoneModel::gethours_key($time);
			$weekday = forPhoneModel::getweek($time);
	    $sql = "SELECT shopid, tabletype,  avgDiningTime FROM `statistics` WHERE shopid = '$shopid' AND section = '$weekday/$time_section' ORDER BY shopid ASC;";
	    $result = mysqli_query($link, $sql);
	    //處理若無資料
	    if(mysqli_fetch_array($result)==null){
	    	$rst_tmp['maxofnumber'] = 0;
	    	$sql = "UPDATE `shops` SET `maxofnumber` = '0', `currentnumber` = '0' WHERE `shops`.`shopid` = '$shopid'";
	    	MySQL::query($sql);
	    	array_push($output_ary, $rst_tmp);
	    	print_r(json_encode($output_ary));
	    	die();
	    }
	    $result = mysqli_query($link, $sql);
	    while($e = mysqli_fetch_array($result)){
		    //$tmp 代表著桌種，$tmp1 代表相近的桌種
		    $tmp = forPhoneModel::getTableType($e[1]);
		    $tmp1 = forPhoneModel::getSimilarType($e[1]);
	    	//計數client表中該店flag=2,4,6,8的人數, 以$rst_pnum[0]表示
	    	$sql_tmp = "SELECT COUNT(*) FROM (SELECT shopid, flag FROM `client` WHERE shopid = '$shopid' AND (flag = '$e[1]' OR ((orderofnum = '$tmp' OR orderofnum = '$tmp1') AND flag = '0'))) AS tmp";
	    	$rst_pnum = MySQL::query_row($sql_tmp);
	    	//找出該店同桌種的總數
	    	$sql_tmp = "SELECT shopid, type, totalnumber FROM `tables` WHERE shopid = '$shopid' AND type = '$e[1]'";
	    	$rst_tnum = MySQL::query_row($sql_tmp);
	    	if($rst_tnum[2] == 0) {
	    		$wait_flag = -1;
	    		$table_status = -1;
	    	}elseif (($rst_tnum[2]-$rst_pnum[0])>0){
	    		$wait_flag = 0;
					$table_status = $rst_tnum[2]-$rst_pnum[0];
	    	}else {
	    		$wait_flag = 1;
	    		$table_status = $e[2];
	    	}
				array_push($tabletype_ary, $e[1]);
				array_push($wait_flag_ary, $wait_flag);
				array_push($table_status_ary, $table_status);
			}
			$tmp = 0;			 // 0 代表第一次進入迴圈
			$tmp_flag = 0; // 0 代表不要array_push, 1 則反之
			for($i=0;$i<sizeof($tabletype_ary);$i++){
				if($tmp==0) {
					$rst_tmp['shopid'] = $shopid;
					$tmp = 1;
				}
				if(isset($tabletype_ary[$i+1]) == NULL) $tmp_flag = 1;
				if($tabletype_ary[$i] == 2){
					$rst_tmp['wait_flag_2'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_2'] = $table_status_ary[$i];
					if($wait_flag_ary[$i]==0){
						$maxofnumber = $maxofnumber + $table_status_ary[$i] * 2;
					}
				}elseif($tabletype_ary[$i] == 4){
					$rst_tmp['wait_flag_4'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_4'] = $table_status_ary[$i];
					if($wait_flag_ary[$i]==0){
						$maxofnumber = $maxofnumber + $table_status_ary[$i] * 4;
					}
				}elseif($tabletype_ary[$i] == 6){
					$rst_tmp['wait_flag_6'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_6'] = $table_status_ary[$i];
					if($wait_flag_ary[$i]==0){
						$maxofnumber = $maxofnumber + $table_status_ary[$i] * 6;
					}
				}elseif($tabletype_ary[$i] == 8){
					$rst_tmp['wait_flag_8'] = $wait_flag_ary[$i];
					$rst_tmp['table_status_8'] = $table_status_ary[$i];
					if($wait_flag_ary[$i]==0){
						$maxofnumber = $maxofnumber + $table_status_ary[$i] * 8;
					}
				}
				if($tmp_flag == 1){
	    		$rst_tmp['maxofnumber'] = $maxofnumber;
	    		$sql = "UPDATE `shops` SET `maxofnumber` = '$maxofnumber' WHERE `shops`.`shopid` = '$shopid'";
	    		MySQL::query($sql);
					array_push($output_ary, $rst_tmp);
				}
			}
			print(json_encode($output_ary));
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function listPhone($str) {
		if ($str['imsi'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$imsi = $new_str['imsi'];
			$link = MySQL::connect();
			$output = array();
			$sql = "SELECT `shopid`, `flag` FROM `client` WHERE `imsi` = '$imsi'";
			$result = mysqli_query($link, $sql);
			while($e = mysqli_fetch_array($result))
				$output[]=$e;
			if ($output == NULL)
				$output = array("fullname"=>0);
	        print(json_encode($output));
	    }else
	    	forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function list_shop($str) {
		if ($str == "try") {
			$link = MySQL::connect();
			$sql = "SELECT `shopid`, `fullname`, `address`, `pic5`, `currentnumber`, `maxofnumber`, `tel`, `rank`, `commentnumber`, `open` FROM shops";
	 		$result = mysqli_query($link, $sql);
	 		while($e = mysqli_fetch_assoc($result))
	 			$output[]=$e;
	 		print(json_encode($output));
		}else			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function setComment($str) {
		if ($str['shopid'] != null && $str['nickname'] != null && $str['comments'] != null && $str['rank'] != null) {
			$new_str = forPhoneModel::SQL_Injection($str);
			$shopid = $new_str['shopid'];
			$nickname = $new_str['nickname'];
			$comments = $new_str['comments'];
			$rank = $new_str['rank'];
			$sql = "INSERT INTO `comment` VALUES (NULL, '$shopid', '$nickname', '$comments', '$rank')";
			MySQL::query($sql);
			print_r("OK");
			$sql = "SELECT `rank`, `commentnumber` FROM `shops` WHERE `shopid` = '$shopid'";
			$row = MySQL::query_row($sql);
			$total_rank = $row[0];
			$commentnumber = $row[1];
			$commentnumber++;
			$total_rank = ($total_rank + $rank)/2;
			$sql = "UPDATE `shops` SET `rank` = '$total_rank', `commentnumber` = '$commentnumber' WHERE `shopid` = '$shopid'";
			MySQL::query($sql);
		}else
			forPhoneModel::errorMsg("You have no permission to read this page!");
	}

	function SQL_Injection($str) {
		if (is_array($str)){
			$new_str = array();
			foreach($str as $key=>$value)
				$new_str[$key] = MySQL::real($value);
			return $new_str;
		}else
			return MySQL::real($str);
	}

	function errorMsg($str) {
		echo "<noscript>".$str."</noscript>";
		echo "<script language='javascript'>";
		echo "alert('".$str."');";
		echo "history.back();";
		echo "</script>";
	}
}
?>
